import uni from '@dcloudio/vite-plugin-uni'
import inject from '@rollup/plugin-inject'
import { resolve } from 'path'
import { defineConfig, loadEnv } from 'vite'
import { createProxy } from './build/vite/proxy'
import getCurMapConfig from './src/common/mapConfig'
import uniReadPagesV3Plugin from './src/router/utils/uni-read-pages-v3'

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  const { VITE_PORT, VITE_PUBLIC_PATH, VITE_PROXY, VITE_THIRD_MAP } = loadEnv(mode, __dirname)

  return {
    base: VITE_PUBLIC_PATH,
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'),
      },
    },
    define: {
      // 各环境变量的配置MAP
      ENV_CONFIG_MAP: {
        // development: { MODE: 'development', ...loadEnv('development', __dirname) },
        testing: { MODE: 'testing', ...loadEnv('testing', __dirname) },
        production: { MODE: 'production', ...loadEnv('production', __dirname) },
      },
    },
    plugins: [
      uni(),

      // 变量
      uniReadPagesV3Plugin({
        pagesJsonDir: resolve(__dirname, './src/pages.json'),
        includes: ['path', 'aliasPath', 'name', 'meta', 'style'],
      }),

      // 地图服务配置
      getCurMapConfig(VITE_THIRD_MAP),

      // 注入全局依赖
      inject({
        EnvScript: [resolve(__dirname, './build/vite/script.js'), 'default'],
        Env: [resolve(__dirname, './build/vite/globalEnvConfig.js'), 'default'],
        CDN: [resolve(__dirname, './src/common/helper/cdn.js'), 'default'],
      }),
    ],

    // css: {
    //   preprocessorOptions: {
    //     scss: {
    //       additionalData: `@import "@/styles/variables.scss";`,
    //       javascriptEnabled: true,
    //     },
    //   },
    // },

    server: {
      host: true,
      // open: true,
      port: VITE_PORT,
      hmr: {
        overlay: true,
      },
      proxy: mode === 'development' ? createProxy(VITE_PROXY) : {},
    },

    //
    build: {
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: mode === 'production' ? true : false,
        },
      },
    },
  }
})
